//
//  HKHeartBeatViewController.m
//  HKTimeKitApp
//
//  Created by huzhaoke1 on 2023/5/18.
//

#import "HKHeartBeatViewController.h"
#import "UIView+properties.h"
#import "HeartBeat.h"
#import "HeartLive.h"
#import "HKToastView.h"

static CGFloat kKSConstSendButtonH = 42.f;

@interface HKHeartBeatViewController ()<HeartBeatPluginDelegate>

@property (strong, nonatomic) HeartLive *live;
@property (nonatomic, strong) UILabel *tipsLabel;
@property (strong, nonatomic) UILabel *label;
@property (nonatomic, assign) NSInteger frequency;
@property (nonatomic, strong) UIButton *endButton;
@property (nonatomic, assign) BOOL hasEnd;
@property (nonatomic, assign) BOOL isStart;
@property (strong, nonatomic) UILabel *timeLabel;
@property (nonatomic, strong) UILabel *errorLabel;
@property (nonatomic, strong) UIView *liveView;

@property (nonatomic, strong) dispatch_queue_t queue;
@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic, assign) NSInteger time;
@property (nonatomic, strong) NSMutableArray *frequencyArray;

@end

@implementation HKHeartBeatViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [HKUITool setStatusBarBackgroundColor:[UIColor whiteColor]];
    //开启测心率方法
    [HeartBeat shareManager].delegate = self;
    [[HeartBeat shareManager]startHeartRatePoint:^(NSDictionary *point) {
        
    } Frequency:^(NSInteger fre) {
        
    } screenView:self.liveView Error:^(NSError *error) {
        
    } ];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.frequencyArray = [@[]mutableCopy];
    [self.userDefinedNaviBar updateTitle:@"测量心率"];
    
    //创建了一个心电图的View
    self.liveView = [[UIView alloc]initWithFrame:CGRectMake((HKScreenWidth-150)/2, self.userDefinedNaviBar.height, 150, 150)];
    self.liveView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.liveView];
    
    
    self.tipsLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, self.liveView.bottom + 10,HKScreenWidth - 20, 60)];
    self.tipsLabel.textColor = [UIColor blackColor];
    self.tipsLabel.font = [UIFont systemFontOfSize:15];
    self.tipsLabel.backgroundColor = [UIColor clearColor];
    self.tipsLabel.textAlignment = NSTextAlignmentCenter;
    self.tipsLabel.numberOfLines = 3;
    self.tipsLabel.text = @"注意事项：请将手指指尖捂在主摄和闪光灯上，直到画面呈现均匀的红色，测量时请保持手指和画面稳定";
    [self.view addSubview:self.tipsLabel];
    
    
    self.label = [[UILabel alloc]initWithFrame:CGRectMake(20, self.tipsLabel.bottom + 10, HKScreenWidth-40, 30)];
    self.label.font = [UIFont systemFontOfSize:15];
    self.label.backgroundColor = [UIColor clearColor];
    self.label.textAlignment = NSTextAlignmentCenter;
    self.label.text = @"当前心率是：0次/分钟";
    [self.view addSubview:self.label];
    
    self.timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, self.label.bottom + 10, HKScreenWidth-40, 30)];
    self.timeLabel.font = [UIFont systemFontOfSize:15];
    self.timeLabel.backgroundColor = [UIColor clearColor];
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.timeLabel];
    
    self.errorLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, self.timeLabel.bottom + 10,HKScreenWidth-40, 30)];
    self.errorLabel.font = [UIFont systemFontOfSize:16];
    self.errorLabel.backgroundColor = [UIColor clearColor];
    self.errorLabel.textAlignment = NSTextAlignmentCenter;
    self.errorLabel.textColor = UIColorFromRGBA(0xEF0800, 1);
    [self.view addSubview:self.errorLabel];

    self.time = 15; //倒计时时间
    self.endButton.top = self.tipsLabel.bottom + 10;
    self.endButton.centerX = self.view.width / 2;
    [self.view addSubview:self.endButton];
}

- (void)downTimer{
    self.queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue);
    dispatch_source_set_timer(self.timer,DISPATCH_TIME_NOW,1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(self.timer, ^{
         if(self.time <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(self.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self endBeat];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                self.time--;
                self.timeLabel.text = [NSString stringWithFormat: @"剩余时间：%lds",(long)self.time];
            });
        }
    });
    dispatch_resume(self.timer);
}

- (void)onTapEnd:(id)sender {
    if (self.frequency == 0) {
        return;
    }
    self.hasEnd = YES;
    [[HeartBeat shareManager] stop];
    [self.endButton setTitle:@"已结束" forState:UIControlStateNormal];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)endBeat{
    if (self.frequency == 0) {
        return;
    }
    self.hasEnd = YES;
    [[HeartBeat shareManager] stop];
    [[HKToastView sharedToastView] showToast:@"心率结束采集"];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 测心率回调

- (void)startHeartDelegateRatePoint:(NSDictionary *)point {
    if (self.hasEnd) return;
//    dispatch_async(dispatch_get_main_queue(), ^{
//        self.errorLabel.text = @"";
//    });
//    NSNumber *n = [[point allValues] firstObject];
    //拿到的数据传给心电图View
//    [self.live drawRateWithPoint:n];
    //NSLog(@"%@",point);
}

- (void)startHeartDelegateRateError:(NSError *)error {
    NSLog(@"%@",error);
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.timer){
            dispatch_source_cancel(self.timer);
            self.time = 15;
            self.timer = nil;
            self.timeLabel.text = @"";
        }
        self.errorLabel.text = error.userInfo[@"content"];
    });
}

- (void)startHeartDelegateRateFrequency:(NSInteger)frequency {
    if (self.hasEnd) return;
    if (frequency < 40) {
        frequency = 40;
    } else if (frequency > 200) {
        frequency = 200;
    }
    if (frequency >= 40){
        if (!self.timer){
            [self downTimer];
        }
    }
    NSLog(@"\n瞬时心率：%ld",frequency);
    dispatch_async(dispatch_get_main_queue(), ^{
        self.errorLabel.text = @"";
        self.label.text = [NSString stringWithFormat:@"当前心率是：%ld次/分钟",(long)frequency];
        self.frequency = frequency;
        [self.frequencyArray addObject:@(frequency)];
        if (self.toGetFrequencyBlock) {
            __block NSInteger sumFrequency = 0;
            [self.frequencyArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                int f = [[NSString stringWithFormat:@"%@",obj] intValue];
                sumFrequency += f;
            }];
            NSInteger avgFrequency = sumFrequency/self.frequencyArray.count;
            NSLog(@"%d",avgFrequency);
            self.toGetFrequencyBlock(avgFrequency);
        }
    });
}

- (UIButton *)endButton{
    if (!_endButton) {
        UIButton *sendButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 93.f, kKSConstSendButtonH)];
        sendButton.backgroundColor = UIColorFromRGBA(0x4448ff, 1);
        sendButton.layer.cornerRadius = kKSConstSendButtonH / 2;
        sendButton.layer.masksToBounds = YES;
        [sendButton setTitleColor:UIColorFromRGBA(0xffffff, 1) forState:UIControlStateNormal];
        [sendButton.titleLabel setFont:[UIFont boldSystemFontOfSize:16.f]];
        [sendButton setTitle:@"结束" forState:UIControlStateNormal];
        [sendButton addTarget:self action:@selector(onTapEnd:) forControlEvents:UIControlEventTouchUpInside];
        sendButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        _endButton = sendButton;
        _endButton.hidden = YES;
    }
    return _endButton;
}

@end
